from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from areas.models import Area
from goods.models import SKU
from users.models import User, Address
from users.serializers import RegisterCreateSerializer, AddressSerializer, TitleAddressSerializer

'''
1.请求方式和路由
GET /users/usernames/(?P<username>\w{5,20})/count/
2.选择三级视图中的哪个
3.添加url
4.

'''
class RegisterUsernameAPIView(APIView):
    def get(self,request,username):
        # 后端接收数据
        # 查询验证
        # 查询数据库
        count=User.objects.filter(username=username).count()
        # 返回相应
        data={
            'count':count,
            'username':username
        }
        # count为0则用户不存在
        # 为1用户存在,返回给前端,前段去判断
        return Response(data)
        pass
# 判断手机号是否存在
class RegisterPhoneAPIView(APIView):
    def get(self,request,mobile):
        count=User.objects.filter(mobile=mobile).count()
        data={
            'count':count,
            'mobile':mobile
        }
        return Response(data)
        pass


# 注册
class RegisterCreateView(CreateAPIView):
    '''
    路径POST/users
    '''
    serializer_class = RegisterCreateSerializer



# # 注册一级视图
# class RegisterOneView(APIView):
#     def post(self,request):
#         #     得到数据
#         body=request.data
#         # body=request.quert_params
#         # get=request.GET
#         # 校验数据
#         serializer=RegisterCreateSerializer(data=body)
#         # 数据入库
#         serializer.is_valid()
#         serializer.save()
#         # 返回相应
#         return Response(serializer.data)
#     pass
# class RegisterTwoView(GenericAPIView):
#     # queryset = User.objects.all()
#     serializer_class = RegisterCreateSerializer
#     def post(self,request):
#         body=request.data
#         serializer=self.get_serializer(data=body)
#         serializer.is_valid()
#         serializer.save()
#         return Response(serializer.data)

# 用户中心
# 首先必须登录才可以查看用户中心页面
# 查询数据库,显示出用户信息
# 返回相应
# 采用get方法(一级视图)
from rest_framework.permissions import IsAuthenticated
from users.serializers import UserDetailSerializer

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

class UserDetailView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request):
        user=request.user
#         序列化器将对象转化为字典
        serializer=UserDetailSerializer(user)
        return Response(serializer.data)

# PUT/users/emails/
# 邮箱验证(获取前端数据,保存到数据库)
# 前端传token用于身份认证
from .serializers import EmailSerializer
from celery_tasks.send_email.tasks import send_email


class EmailView(APIView):
    def put(self,request):
        data=request.data
        user=request.user
        serializer=EmailSerializer(instance=user,data=data)
        serializer.is_valid()
        serializer.save()


        from .utils  import generate_verify_email_url
        verify_url=generate_verify_email_url(user.id,user.email)

        send_email.delay(data.get('email'),verify_url)
        # send_email.delay('2992850128@qq.com','ppppp')
        return Response(serializer.data)

from rest_framework.generics import UpdateAPIView
# 三级视图更新邮箱
class EmailThreeView(UpdateAPIView):
    # 用户必须登录才能访问用户中心页面,所以需要先认证
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer
    def get_object(self):
        return self.request.user


# GET /users/emails/verification/
# 验证邮箱链接
# 获取token,检验token的用户信息是否在数据库中,是修改email_active
# 获取数据
# 校验数据
# 数据入库
# 返回相应
from rest_framework import status
from users.utils import    check_userid, generate_verify_email_url


class VerificationEmailView(APIView):
    def get(self,request):
        # 查询字符串
        token=request.query_params.get('token')
        if token is  None:
            return Response({'message':'缺少token'},status=status.HTTP_400_BAD_REQUEST)
        dict=check_userid(token)
        if dict is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        id=dict.get('id')
        email=dict.get('email')
        try:
            user=User.objects.get(id=id,email=email)
            # filter获取查询结果集,集合没有单个属性
            # user=User.objects.filter(id=id).filter(email=email)
            # user=user[0]
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user.email_active=True
        user.save()
        return Response({
            'messages':'ok'
        })
# 用户中心
# GET/users/infos/
from users.serializers import UserCenterSerializer
class UserCenterAPIView(APIView):
    Permission_class=[IsAuthenticated]
    def get(self,request):
        user=request.user
        serializer=UserCenterSerializer(user)
        return Response(serializer.data)
# 更新邮箱# PUT/users/emails/
from users.serializers import UpdateEmailSerializer
class UpdateEmailAPIView(APIView):
    Permission_class=[IsAuthenticated]
    def put(self,request):
        data=request.data
        user=request.user
        serializer=UpdateEmailSerializer(instance=user,data=data)
        serializer.is_valid()
        serializer.save()
        # send_email(to_email, verify_url)
        verify_url=generate_verify_email_url(user.id,data['email'])

        # send_email.delay(data.get('email'),verify_url)
        send_email.delay(data['email'],verify_url)
        return Response(serializer.data)

#     验证邮箱GET /users/emails/verification/


class VerializationEmailAPIView(APIView):
    def get(self,request):
        token=request.query_params.get('token')
        try:
            dict=check_userid(token)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        id=dict.get('id')
        email=dict.get('email')
        try:
            user=User.objects.get(id=id,email=email)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # user=User.objects.filter(id=id).filter(email=email)
        user.email_active=True

        user.save()
        return Response({'message':'ok'})

# 用户地址保存
# 必须登录才能访问
class  AddressView(APIView):
    permission_classes = [IsAuthenticated]
    # 增加地址
    def post(self,request):
        data=request.data
        serializer=AddressSerializer(data=data,context={'request':request,
                                                        'view':self
                                                        })
        serializer.is_valid()
        serializer.save()
        return Response(serializer.data)

    # 地址列表(查询数据库)
    def get(self,request):
        addresses=Address.objects.filter(is_deleted=False)
        serializer=AddressSerializer(addresses,many=True)
        data={
            'addresses':serializer.data,
            'limit':'20',
            'default_address_id':request.user.default_address_id,

        }
        return Response(data)
    # 删除地址
class DeleteAddressAPIView(APIView):
    permission_classes = [IsAuthenticated]
    def delete(self,request,pk):
        try:
            address=Address.objects.get(id=pk)
        except Address.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        address.is_deleted=True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # 修改信息
    def put(self, request,pk):
        data=request.data
        try:
            address=Address.objects.get(id=pk)
        except Address.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        serializer=AddressSerializer(instance=address,data=data)
        serializer.is_valid()
        serializer.save()
        return Response(serializer.data)
        pass
# 修改默认地址    user.default_address_id=pk
class ChangeDefaultAddressAPIView(APIView):
    def put(self,request,pk):
        try:
            address=Address.objects.get(id=pk)
        except Address.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user=request.user
        user.default_address_id=pk
        user.save()
        return Response(status=status.HTTP_200_OK)
# 修改标签
class ChangeTitleAPIView(APIView):
    def put(self,request,pk):
        data=request.data
        try:
            address=Address.objects.get(id=pk)
        except Address.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        serializer=TitleAddressSerializer(address,data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'message':'ok'})
        pass


# 三级视图
class AddressTwoView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer


# POST /users/browerhistories/(新增用户浏览记录)

# 用户浏览记录
# 首先需要登录(登录用户才有浏览记录),前端给我传token sku_id
# 点击详情页时增加用户浏览记录(保存啥  user_id和goods_id)
# 缓存在redis中(访问能快一点)
from .serializers import AddUserBrowerhistoriesSerializer,GetUserBrowerhistoriesSerializer
class AddUserBrowerhistoriesAPIView(CreateAPIView):
    # 登录
    permission_classes = [IsAuthenticated]
    # queryset =
    serializer_class = AddUserBrowerhistoriesSerializer

    def get(self,request):
        '''
        用户id,根据用户id查询redis中sku_id,根据sku_id查询sku对象,序列化,返回给前端
        '''
        user_id=request.user.id
        redis_conn=get_redis_connection('history')
        sku_id_list=redis_conn.lrange('history_%s' % user_id,0,-1)
        list=[]
        for sku_id in sku_id_list:
            sku=SKU.objects.get(pk=sku_id)
            list.append(sku)
        serializer=GetUserBrowerhistoriesSerializer(list,many=True)

        return Response(serializer.data)












